package org.itboys.pay.weixin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.pay.constant.PayConstants;
import org.itboys.pay.tools.XMLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 微信退款工具类
 * @author huml
 *
 */
public class WXPayRefund {
	private static Logger logger = LoggerFactory.getLogger(WXPayRefund.class);
	/**
	 * 微信退款
	 * @param appId
	 *            微信appid
	 * @param mchId
	 *            微信商户号
	 * @param appKey
	 *            支付key
	 * @param transactionId
	 *            在notify_url中解析微信返回的信息获取到 transaction_id
	 * @param outTradeNo
	 *            支付时传给微信的订单号
	 * @param outFefundNo
	 *            我们自己设定的退款申请号
	 * @param totalFee
	 *            退款金额,单位为分
	 * @param filePath
	 *            证书存放路径
	 * @return
	 * @throws Exception
	 */
	public static String weixinRefund(String appId, String mchId, String appKey,
			String transactionId, String outTradeNo, String outFefundNo,
			Integer totalFee, Integer refoundFee, String filePath) throws Exception{
		String result = null;
		result = WXPayRefund.refund(appId, mchId, appKey, transactionId, outTradeNo, outFefundNo, totalFee, refoundFee, filePath);
		logger.info("*************refund result***************"+result);
		if (null != result) {
			Map<String, Object> map = XMLUtil.doXMLParse(result);
			String returnCode = (String)map.get(PayConstants.WeixinPay.RETURN_CODE);
			String resultCode = (String)map.get(PayConstants.WeixinPay.RESULT_CODE);
			if(returnCode.toLowerCase().equals(CommonConstants.SUCCESS) && resultCode.toLowerCase().equals(CommonConstants.SUCCESS)){
				return CommonConstants.SUCCESS;
			}
		}
		return CommonConstants.FAIL;
	}

	/**
	 * 
	 * @param appId
	 *            微信appid
	 * @param mchId
	 *            微信商户号
	 * @param appKey
	 *            支付key
	 * @param transactionId
	 *            在notify_url中解析微信返回的信息获取到 transaction_id
	 * @param outTradeNo
	 *            支付时传给微信的订单号
	 * @param outFefundNo
	 *            我们自己设定的退款申请号
	 * @param totalFee
	 *            退款金额,单位为分
	 * @param filePath
	 *            证书存放路径
	 * @return
	 * @throws Exception
	 */
	private static String refund(String appId, String mchId, String appKey,
			String transactionId, String outTradeNo, String outFefundNo,
			Integer totalFee, Integer refoundFee, String filePath) throws Exception {
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", appId);// appid
		parameters.put("mch_id", mchId);// 商户号
		parameters.put("nonce_str", CreateNoncestr());
		// 在notify_url中解析微信返回的信息获取到 transaction_id，此项不是必填，详细请看上图文档
		if (StringUtils.isNotBlank(transactionId)) {
			parameters.put("transaction_id", transactionId);
		}
		if (StringUtils.isNotBlank(outTradeNo)) {
			parameters.put("out_trade_no", outTradeNo);// 支付时传给微信的订单号
		}
		parameters.put("out_refund_no", outFefundNo);// 我们自己设定的退款申请号，约束为UK

		parameters.put("total_fee", String.valueOf(totalFee));// 单位为分
		parameters.put("refund_fee", String.valueOf(refoundFee));// 单位为分
		parameters.put("op_user_id", mchId);// 操作人员,默认为商户账号
		String sign = createSign("utf-8", appKey, parameters);
		parameters.put("sign", sign);

		String reuqestXml = getRequestXml(parameters);
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(new File(filePath));// 放退款证书的路径
		try {
			keyStore.load(instream, mchId.toCharArray());
		} finally {
			instream.close();
		}
		SSLContext sslcontext = SSLContexts.custom()
				.loadKeyMaterial(keyStore, mchId.toCharArray()).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(
					"https://api.mch.weixin.qq.com/secapi/pay/refund");// 退款接口

			StringEntity reqEntity = new StringEntity(reuqestXml);
			// 设置类型
			reqEntity.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(reqEntity);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("Response content length: "
							+ entity.getContentLength());
					BufferedReader bufferedReader = new BufferedReader(
							new InputStreamReader(entity.getContent(), "UTF-8"));
					String text;
					while ((text = bufferedReader.readLine()) != null) {
						result += text;
					}
					logger.info("*******************refund result***" + result);
				}
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
		return result;
	}

	private static String CreateNoncestr() {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < 16; i++) {
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}

	private static String createSign(String charSet, String appKey,
			SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + appKey);
		String sign = Digests.md5(sb.toString()).toUpperCase();
		return sign;
	}

	private static String getRequestXml(SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)
					|| "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}
}